package com.pomr.controller.sys;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.Role;
import com.pomr.model.sys.User;
import com.pomr.service.sys.AgencyService;
import com.pomr.service.sys.UserService;
/**
 * 用户管理
 * @author Administrator
 *
 */
import com.pomr.util.common.CallMessage;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;
import com.pomr.util.page.Page;
import com.pomr.util.page.PageParam;
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	@Qualifier("userServiceImpl")
	private UserService userService;
	
	@Autowired
	@Qualifier("agencyServiceImpl")
	private AgencyService agencyService;
	
	/**
	 * 添加
	 * @return
	 */
	@RequestMapping(value="/insert",method=RequestMethod.GET)
	public String insert(HttpSession session, Model model){
		//查询当前用户所属机构
		User user = (User) session.getAttribute("user");
		List<Agency> agencys = null;
		List<Role> roles = null;
		try {
			agencys = userService.findAgencysWithUser(user);
			roles = userService.findRolesWithUser(user);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(agencys == null){
			agencys = new ArrayList<Agency>();
		}
		if(roles == null){
			roles = new ArrayList<Role>();
		}
		model.addAttribute("agencys", agencys);
		model.addAttribute("roles", roles);
		return "sys/user/insert";
	}
	
	/**
	 * 添加用户前
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/inter-insertbefore",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData insertUserBefore(HttpServletRequest request){
		ResponseData pd = null;
		List<Agency> agencys = null;
		List<Role> roles = null;
		try {
			User user = JWT.findUserByToken(request);
			agencys = agencyService.findAgencysOfUser(user);
			roles = userService.findRolesWithUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		if(agencys == null){
			agencys = new ArrayList<Agency>();
		}
		if(roles == null){
			roles = new ArrayList<Role>();
		}
		pd = ResponseData.ok();
		pd.putDataValue("agencys", agencys);
		pd.putDataValue("roles", roles);
		return pd;
	}
	
	
	@RequestMapping(value="/inter-insert",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData insertUser(HttpServletRequest request,@RequestBody User user){
		ResponseData pd = null;
		try {
			if(userService.insertUser(user)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-delete",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData deleteUserInter(HttpServletRequest request,@RequestBody Map<String,Object> map){
		ResponseData pd = null;
		try {
			String[] ids = map.get("id").toString().split(",");
			List<String> idl = Arrays.asList(ids);
			if(userService.deleteUsersInter(idl)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-editbefore",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editUserInterBefore(HttpServletRequest request,@RequestBody User user){
		ResponseData pd = null;
		try {
			user = userService.serachUser(user);
			if(user == null){
				pd = ResponseData.custom("没有找到该用户");
			}else{
				pd = ResponseData.ok();
				pd.putDataValue("user", user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-edit",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editUserInter(HttpServletRequest request,@RequestBody User user){
		ResponseData pd = null;
		try {
			if(userService.editUser(user)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.custom("更新用户失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-editUserBase",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editUserBase(HttpServletRequest request,@RequestBody User user){
		ResponseData pd = null;
		try {
			if(userService.editUserBase(user)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.custom("更新用户失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-editUserStatus",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData editUserStatus(HttpServletRequest request,@RequestBody User user){
		ResponseData pd = null;
		try {
			if(userService.editUserStatus(user)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.custom("更新用户状态失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-searchbefore",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData searchUserBefore(HttpServletRequest request){
		ResponseData pd = null;
		List<Agency> agencys = null;
		try {
			User user  = JWT.findUserByToken(request);
			agencys = agencyService.findAgencysOfUser(user);
			pd = ResponseData.ok();
			pd.putDataValue("agencys", agencys);
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
			return pd;
		}
		return pd;
	}
	
	@RequestMapping(value="/inter-search",method=RequestMethod.POST)
	@ResponseBody
	public Page<List<User>> searchUsers(HttpServletRequest request,@RequestBody Map<String,Object> map){
		Page<List<User>> p = new Page<List<User>>();
		try{
			User u = new User();
			u.setName(map.get("username")==null?null:map.get("username").toString());
			u.setTel(map.get("usertel")==null?null:map.get("usertel").toString());
			if(map.get("useragency")!=null && !map.get("useragency").toString().equals("")){
				Agency agency = new Agency();
				agency.setId(Integer.valueOf(map.get("useragency").toString()));
				u.setAgency(agency);
			}
			u.setStatus(map.get("userstatus")==null?null:map.get("userstatus").toString());
			p.setCunrrentPage(Integer.valueOf(map.get("page").toString()));
			p.setPageSize(Integer.valueOf(map.get("limit").toString()));
			p = userService.findUsersInter(u, p);
		}catch (Exception e) {
			e.printStackTrace();
			p = null;
		}
		return p;
	}
	
	
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public String insert(User user, Model model){
		try {
			if(userService.insertUser(user)){
				model.addAttribute("msg", "添加成功");
			}else{
				model.addAttribute("msg", "添加失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "sys/user/insert";
	}
	
	
	@RequestMapping(value="/inter-save",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData save(@RequestBody User user){
//		User user = (User) map.get("user");
//		Role role = (Role) map.get("role");
//		Agency agency = (Agency) map.get("agency");
//		user.setAgency(agency);
//		user.setRole(role);
		System.out.println(user.getRole().getId());
		ResponseData pd = null;
		try {
			if(userService.insertUser(user)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		
		return pd;
	}
	
	/**
	 * 检查用户名唯一
	 * @return
	 */
	@RequestMapping(value="/test",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData testUser(@RequestBody Map<String,Object> map){
		ResponseData pd = null;
		String uname = map.get("uname").toString().trim();
		if(uname == null || "".equals(uname)){
			pd = ResponseData.custom("用户名为必填项");
		}else{
			try {
				if(userService.testUser(uname)){
					pd = ResponseData.custom("用户名已存在");
				}else{
					pd = ResponseData.ok();
				}
			} catch (Exception e) {
				e.printStackTrace();
				pd = ResponseData.exceptionError();
			}
		}
		return pd;
	}
	
	/**
	 * 查询
	 * @return
	 */
	@RequestMapping(value="/select",method=RequestMethod.GET)
	public String select(HttpSession session, Model model){
		//查询当前用户所属机构
		User user = (User) session.getAttribute("user");
		List<Agency> agencys = null;
		List<Role> roles = null;
		try {
			agencys = userService.findAgencysWithUser(user);
			roles = userService.findRolesWithUser(user);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(agencys == null){
			agencys = new ArrayList<Agency>();
		}
		if(roles == null){
			roles = new ArrayList<Role>();
		}
		model.addAttribute("agencys", agencys);
		model.addAttribute("roles", roles);
		return "sys/user/select";
	}
	
	/**
	 * 查询用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/selectusers",method=RequestMethod.GET)
	public String selectUsers(User user,String page,Model model){
		Page<List<User>> p = null;
		try {
			p = userService.findUsers(user, page);
		} catch (Exception e) {
			e.printStackTrace();
			p.setRows(new ArrayList<User>());
		}
		if(p.getRows() == null){
			p.setRows(new ArrayList<User>());
		}
		model.addAttribute("page", p);
		return "sys/user/show";
	}
	
	@RequestMapping(value="/inter-select",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<User>> selectUsersInter(HttpServletRequest request){
		
		Page<List<User>> p = null;
		try {
			String page = request.getParameter("cunrrentPage");
			String psize = request.getParameter("pageSize");
			String userstr = request.getParameter("djson");
			User user = JSON.parseObject(userstr, User.class);
			if(user == null){
				System.out.println("------");
			}else{
				System.out.println(user.getAgency().getId());
			}
			Page<List<User>> page1 = new Page<List<User>>();
			page1.setPageSize(Integer.valueOf(psize));
			page1.setCunrrentPage(Integer.valueOf(page));
			p = userService.findUsersInter(user, page1);
		} catch (Exception e) {
			e.printStackTrace();
			p = new Page<List<User>>();
			p.setRows(new ArrayList<User>());
		}
		if(p.getRows() == null){
			p.setRows(new ArrayList<User>());
		}
		System.out.println(p.getRows().size());
		return p;
	}
	
	@RequestMapping(value="/inter-searchByCond",method=RequestMethod.GET)
	@ResponseBody
	public Page<List<User>> searchUsers(HttpServletRequest request,PageParam param) throws Exception{
		String page = param.getPage();
		String limit = param.getLimit();
		Map<String, String> map = param.getParams();
		return userService.findUsersByCond(page, limit, map);
	}
	
	/**
	 * 重置密码
	 * @return
	 */
	@RequestMapping(value="/inter-pwd",method=RequestMethod.POST)
	@ResponseBody
	public ResponseData updatePwd(@RequestBody User user){
		ResponseData pd = null;
		try {
			if(userService.updatePwd(user)){
				pd = ResponseData.ok();
			}else{
				pd = ResponseData.fail();
			}
		} catch (Exception e) {
			e.printStackTrace();
			pd = ResponseData.exceptionError();
		}
		return pd;
	}
	
	

}
